package com.gaoda.booksystem.web.sys;

import com.gaoda.booksystem.entity.Book;
import com.gaoda.booksystem.sysService.SysBookService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
public class BookManage {

    //分页
    private static final long serialVersionUID = 1L;
    private static final int PAGE_COUNT = 3;//每页显示记录数

    @Autowired
    SysBookService sysBookService;

    //模糊查询显示用户列表 + 分页
    @RequestMapping("/bookList")
    public String queryBookList(String bookName, String bookPublishers, String bookType, Model model, HttpServletRequest request){
        //默认当前页
        int currentPage = 1;
        String page = request.getParameter("page");
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }

      /*  System.out.println(currentPage+"*****************");
        int pagenew=currentPage;
        currentPage=(currentPage-1)*PAGE_COUNT;
        int  pageCount=PAGE_COUNT*pagenew;*/

        System.out.println(currentPage+","+PAGE_COUNT);
        List<Book> list = sysBookService.queryBooks(bookName,bookPublishers,bookType,currentPage,PAGE_COUNT);
        System.out.println(list);
        int totalPage = sysBookService.getTotalPage(PAGE_COUNT, bookName, bookPublishers, bookType);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("list",list);
        model.addAttribute("bookName",bookName);
        model.addAttribute("bookPublishers",bookPublishers);
        model.addAttribute("bookType",bookType);
        return "sys/bookManage";
    }

    //逻辑删除书籍
    @RequestMapping("/deleteBook")
    @ResponseBody   //声明返回的数据为json格式
    public String deleteBook(int bookNumber){
        try{
            System.out.println("delete" + bookNumber);
            sysBookService.deleteBookByBookNum(bookNumber);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    //跳转到添加书籍的页面
    @RequestMapping("/jumpToAddBook")
    public String jumpToAddBook(){
        return "sys/addBook";
    }

    //添加图书
    @RequestMapping("/addBook")
    public String addBook(@RequestParam("file") MultipartFile myfile, Book book) throws IOException {
        Date date = new Date();
        book.setBookTime(date);
        String newFileName = "";
        String oldFileName = myfile.getOriginalFilename();//获取上传文件原名
        String saveFilePath = "D://gaoda/booksystem/pic";
        if (myfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新图片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 将内存中的数据写入磁盘
            try {
                myfile.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        book.setPhoto(newFileName);
        int bookNumber = sysBookService.findBookId()+1;
        book.setBookNumber(bookNumber);
        sysBookService.addBook(book);
        return "redirect:bookList";
    }

    //显示书籍详细信息
    @RequestMapping("/showBookDetail")
    public String userDetail(Model model,int bookNumber){
        Book book = sysBookService.findByBookNum(bookNumber);
        model.addAttribute("book",book);
        return "sys/bookDetail";
    }

    //修改书籍信息
    @RequestMapping("/updateBookManage")
    public String updateUserManage(@RequestParam("file") MultipartFile myfile, Book book) throws IOException {
        String newFileName = "";
        String oldFileName = myfile.getOriginalFilename();//获取上传文件原名
        String saveFilePath = "D://gaoda/booksystem/pic";
        if (myfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新图片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 将内存中的数据写入磁盘
            try {
                myfile.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        book.setPhoto(newFileName);
        sysBookService.updateBook(book);
        return "redirect:/bookList";
    }

    //导出书籍信息
    @RequestMapping(value = "/loadSysBook", method = RequestMethod.GET)
    public void loadBook(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("书籍信息表");
        //获取数据
        List<Book> bookList = sysBookService.bookList();

        //设置要导出的文件的名字
        String fileName = "BookList" + ".xls";

        //新增数据行，并且设置单元格数据
        int rowNum = 1;

        //headers表示excel表中第一行的表头
        String[] headers = {"书号", "书名", "作者", "出版社", "入库时间", "简介", "总数", "余量"};

        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Book book : bookList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(book.getBookNumber());
            row1.createCell(1).setCellValue(book.getBookName());
            row1.createCell(2).setCellValue(book.getBookAuthor());
            row1.createCell(3).setCellValue(book.getBookPublishers());
            row1.createCell(4).setCellValue(sdf.format(book.getBookTime()));
            row1.createCell(5).setCellValue(book.getBrief());
            row1.createCell(6).setCellValue(book.getBookAllNum());
            row1.createCell(7).setCellValue(book.getBookNum());
            rowNum++;
        }

        //根据内容自动调整列宽
        HSSFSheet hssfSheet = workbook.getSheetAt(0);
        hssfSheet.autoSizeColumn((short)0);
        hssfSheet.autoSizeColumn((short)1);
        hssfSheet.autoSizeColumn((short)2);
        hssfSheet.autoSizeColumn((short)3);
        hssfSheet.autoSizeColumn((short)4);
        hssfSheet.autoSizeColumn((short)6);
        hssfSheet.autoSizeColumn((short)7);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+ fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}
